package remoteControl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * this class listen to the remote control(the server side)
 * @author ran
 *
 */
public class listenToRemoteControl{
	/**
	 * this method override the run method of runnable
	 * @return
	 */
	public String run(){
		ServerSocket serverSocket=null;
	    PrintWriter out = null;
	    BufferedReader in = null;
	    //listen to the port of the remote control
	    try { 
	     serverSocket = new ServerSocket(12345);
	     System.out.println("Server started");
	    }
	    catch (IOException e) { 
	     System.err.println("Cannot listen on port 4444");
	     System.exit(-1);
	    }
	    Socket clientSocket=null;
	    String path=null;
	    try { 
	     clientSocket=serverSocket.accept(); 
	     out=new PrintWriter(clientSocket.getOutputStream(),true);
	     in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
	     // server code here...
	     MyProtocol mp=new MyProtocol(in,out);
	     path = mp.run();
	    }
	    catch (IOException e) { 
	     System.err.println("Accept failed");
	     System.exit(-1);
	    }
	    finally {
	     if (clientSocket != null)
			try {
				clientSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
	     if (serverSocket != null)
			try {
				serverSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	    return path;
	}
}
